08. Interfaces

Interfaces

ND079 C1 L3 A07 Interface

Interfaces allow us to avoid hardcoding features in an application. We can move specific implementation details into subclasses, and then use an interface to communicate between the application and the subclasses.

Interfaces vs Abstract Classes

Here are some of the similarities and differences between abstract classes and interfaces:

Abstract class

  • Can have class variables.
  • Can have both abstract methods and concrete methods that are shared with the subclasses.
  • Can have instance variables, i.e. variables that are specific to individual subclasses.
  • Subclasses can only extend one class.

Interfaces

  • Can have class variables.
  • Every method in an interface is abstract.
  • Cannot have instance variables. Variables in an interface must be the same for every class implementing the interface.
  • Classes can implement more than one interface and have multiple inheritance.

When to Use an Interface

We use an interface when:

  • We expect unrelated classes will be implementing our interface.
  • We want to support multiple inheritance.
  • We want to specify the behavior for a data type, but we do not care about the implementation.

QUIZ QUESTION::

For each of the descriptions below, does it better describe and interface or an abstract class?

ANSWER CHOICES:



Description

Interface or Abstract class

We expect unrelated classes will be implementing our super class.

We want to support multiple inheritance.

We want subclasses to have instance variables.

We want to provide concrete methods for subclasses

We want to make use of both concrete methods and abstract methods for subclasses.

SOLUTION:

Description

Interface or Abstract class

We want subclasses to have instance variables.

We want to provide concrete methods for subclasses

We want to make use of both concrete methods and abstract methods for subclasses.

We want subclasses to have instance variables.

We want to provide concrete methods for subclasses

We want to make use of both concrete methods and abstract methods for subclasses.

We want subclasses to have instance variables.

We want to provide concrete methods for subclasses

We want to make use of both concrete methods and abstract methods for subclasses.

We expect unrelated classes will be implementing our super class.

We want to support multiple inheritance.

We expect unrelated classes will be implementing our super class.

We want to support multiple inheritance.